<template>

  <el-card class="box-card">
    <div class="table-header">
      <div>
        <el-input
                style="width: 200px"
                v-model="urlParams.search"
                placeholder="请输入账号"
                clearable
                @clear="onSearch"
                @keyup.enter="onSearch"
        ></el-input>
        &nbsp
        <el-input
                style="width: 200px"
                v-model="urlParams.first_name"
                placeholder="请输入姓名"
                clearable
                @clear="onSearch"
                @keyup.enter="onSearch"
        ></el-input>
        <el-button type="primary" style="margin-left: 10px" @click="onSearch"><el-icon><search /></el-icon>查询</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="SearchReset"><el-icon><RefreshRight /></el-icon>重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="createDialogVisible = true"><el-icon><plus /></el-icon>新增</el-button>
        <!--展示列弹出框-->
        <el-popover placement="left" :width="100" v-model:visible="columnVisible" trigger="contextmenu">
          <template #reference>
            <el-button type="primary" @click="columnVisible = true"><el-icon><setting /></el-icon>&nbsp;展示列</el-button>
          </template>
              <el-checkbox v-model="showColumn.username">账号</el-checkbox>
              <el-checkbox v-model="showColumn.role">角色</el-checkbox>
              <el-checkbox v-model="showColumn.first_name">姓名</el-checkbox>
              <el-checkbox v-model="showColumn.sex">性别</el-checkbox>
              <el-checkbox v-model="showColumn.age">年龄</el-checkbox>
              <el-checkbox v-model="showColumn.email">邮箱</el-checkbox>
              <el-checkbox v-model="showColumn.mobile">手机号码</el-checkbox>
              <el-checkbox v-model="showColumn.is_active">状态</el-checkbox>
              <el-checkbox v-model="showColumn.date_joined">加入日期</el-checkbox>
            <div style="text-align: right; margin: 0">
              <el-button size="small" type="Default" @click="columnVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="saveColumn">确认</el-button>
            </div>

        </el-popover>

      </div>
    </div>

    <!--数据表格-->
    <el-table
            :data="tableData"
            style="width: 100%"
            stripe
            :header-cell-style="{background: '#F8F8F8',textAlign: 'center' }"
            v-loading="loading"
            @cell-dblclick="dbclick"
            :show-overflow-tooltip="true"
            height="390px"
            :row-style="{height: '0'}"
            :cell-style="{padding: '4.7px',textAlign: 'center'}"
    >
        <template #empty><el-empty description="暂无数据" /></template>
        <el-table-column prop="username" label="账号"  v-if="showColumn.username"/>
        <el-table-column prop="sex" label="角色"  v-if="showColumn.role">
              <template #default="scope">
                  <span  v-if="scope.row.role === 1">管理员</span>
                  <span  v-if="scope.row.role === 2">普通用户</span>
            </template>
       </el-table-column>
        <el-table-column prop="first_name" label="姓名"  v-if="showColumn.first_name"/>
        <el-table-column prop="sex" label="性别"  v-if="showColumn.sex">
              <template #default="scope">
                  <span  v-if="scope.row.sex === 1">男</span>
                  <span  v-if="scope.row.sex === 2">女</span>
            </template>
       </el-table-column>
        <el-table-column prop="age" label="年龄"  v-if="showColumn.age"/>
        <el-table-column prop="email" label="邮箱"  v-if="showColumn.email"/>
        <el-table-column prop="mobile" label="手机号码" width="120px" v-if="showColumn.mobile"/>
        <el-table-column prop="is_active" label="状态"  v-if="showColumn.is_active">
              <template #default="scope">
              <el-tag  type="warning" v-if="scope.row.is_active === false">禁用</el-tag>
              <el-tag  type="success" v-if="scope.row.is_active === true">启用</el-tag>
            </template>
       </el-table-column>
        <el-table-column prop="date_joined" label="注册时间" width="165px" sortable v-if="showColumn.date_joined"/>
      <!--操作栏-->
      <el-table-column fixed="right" label="操作" width="280px" >
        <template #default="scope">
          <el-button type="primary" plain size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-popconfirm
            title="是否确定删除"
            @confirm="handleDel(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button type="danger" plain size="small">删除</el-button>
            </template>
          </el-popconfirm>
          <el-button  type="info" plain size="small" @click="handleDesc(scope.$index, scope.row)">详情</el-button>
          <el-button  type="warning" plain size="small" @click="handlePawword(scope.$index, scope.row)">重置密码</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--分页-->
    <div style="margin-top: 20px">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="->, total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-card>

   <!--修改密码对话框-->
  <el-dialog
    v-model="UserPasswordDialog"
    width="30%"
    title="修改密码"
  >
    <el-form :model="UserPasswordForm" label-width="100px" :rules="rules" ref="UserPasswordForm">
      <el-form-item label="账号：" prop="username">
        <el-input
          v-model="UserPasswordForm.username"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码：" prop="new_password">
        <el-input
            v-model="UserPasswordForm.new_password"
            type="password"
            show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="再次确认：" prop="confirm_password">
        <el-input
            v-model="UserPasswordForm.confirm_password"
            type="password"
            show-password
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="UserPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePasswordSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>


  <UserEdit v-model:visible="editDialogVisible" :row="row" @getData="getData"></UserEdit>
  <UserCreate v-model:visible="createDialogVisible"></UserCreate>
  <UserDescribe v-model:visible="descDialogVisible" :row="row" @getData="getData"></UserDescribe>

</template>

<script>
    import UserDescribe from "./UserDescribe.vue";
    import UserEdit from "./UserEdit.vue";
    import UserCreate from "./UserCreate.vue";
    export default {
        data() {
          const checkNewPassword = (rule, value, callback) => {
                if (value != this.UserPasswordForm.new_password) {
                    callback(new Error('两次输入密码不一致！'))
                } else {
                    return callback()
                }
           };
          return {
            loading: false,
            tableData: [],
            total: 0,  // 总数据条数
            pageSize: 10, // 默认每页的数据条数
            currentPage: 1,  // 默认开始页码
            urlParams: {  // URL查询参数
              page_num: 1,
              page_size: 10,
              search: '',
              first_name: ''
            },
            UserPasswordForm: {
                username: '',
                new_password: '',
                confirm_password: ''
            },
            rules: {
                new_password: [
                    {required: true, message: '请输入新密码', trigger: 'blur'},
                    {min: 6, message: '密码长度应不小于6个字符', trigger: 'blur'},
                ],
                confirm_password: [
                    {required: true, message: '请确认新密码', trigger: 'blur'},
                    {min: 6, message: '密码长度应不小于6个字符', trigger: 'blur'},
                    {validator: checkNewPassword, trigger: 'blur'}
                ]
            },
            UserPasswordDialog: false,   //密码修改对话框
            editDialogVisible: false,
            descDialogVisible: false,
            row: '',
            createDialogVisible: false,
            showColumn: {
              username: true,
              role: true,
              first_name: true,
              age: true,
              sex: true,
              email: true,
              is_active: true,
              last_login: true,
              date_joined: true,
              mobile: true
            },
            columnVisible: false // 展示与隐藏
          }
        },
        mounted() {
          this.getData();
          // 从浏览器本地存储获取历史展示列
          const columnSet = localStorage.getItem(this.$route.path + '-columnSet')
          // 如果本地有存储则使用
          if(columnSet) {
            this.showColumn = JSON.parse(columnSet)
          }
        },
        methods: {
          //修改密码
          handlePawword(index, row) {
              this.UserPasswordForm.username = row.username;
              this.UserPasswordDialog = true;
          },
          //提交密码
          changePasswordSubmit() {
                // 提交前预验证
                this.$refs.UserPasswordForm.validate((valid) => { // 回调函数中valid布尔值
                    if (valid) {
                       this.$http.put('/change_password/', this.UserPasswordForm)
                        .then(res => {
                            if (res.data.code === 200) {
                                this.$message.success(res.data.msg);
                                this.UserPasswordDialog = false;
                            }
                        })
                        .catch((error) => {
                            this.$message.error('服务端接口请求错误！'+ error)
                        })
                    } else {
                        this.$message.warning('密码格式错误！')
                    }
                });
            },
          getData() {
            // 处理URL查询参数
              if(!this.urlParams.search) {
                  delete this.urlParams.search;
              }
              if(!this.urlParams.first_name) {
                  delete this.urlParams.first_name;
              }
            this.loading = true;
            this.$http.get('/config/user/', {params: this.urlParams})
              .then(res => {
                console.log(res.data.data,123);
                this.tableData = res.data.data;
                this.total = res.data.count;
                this.loading = false;
              })
          },
           // 分页：监听【选择每页数量】的事件
          handleSizeChange(pageSize) {
              // console.log(pageSize)
              this.pageSize = pageSize; // 重新设置分页显示
              this.urlParams.page_size = pageSize;  // 将最新值设置到数据里，用于下面用新值重新获取数据
              this.getData()
          },
          // 分页：监听【点击页码】的事件
          handleCurrentChange(currentPage) {
              // console.log(currentPage)
              this.currentPage = currentPage; // 重新设置分页显示
              this.urlParams.page_num = currentPage;
              this.getData()
          },
          handleEdit(index, row) {
            console.log(index,row);
            this.editDialogVisible = true;
            this.row = row;
          },
          handleDesc(index, row) {
            // console.log(index,row);
            this.descDialogVisible = true;
            this.row = row;
          },
          //双击显示详情
          dbclick(row, column, cell, event){
            this.descDialogVisible = true;
            this.row = row;
          },
          handleDel(index, row) {
              this.$http.delete('/config/user/'+ row.id + '/')
                  .then(res => {
                    if(res.data.code === 200) {
                      this.$message.success('删除成功');
                      this.tableData.splice(index, 1); // 根据表格索引临时删除数据
                    } else {
                      this.$message.error(res.data.msg);
                    }
                  })
                .catch(() => {
                  // this.$message.info('取消');
                })
          },
          onSearch() {
            this.getData();
          },
          //重置查询的数据
          SearchReset() {
            this.urlParams.search = '';
            this.urlParams.first_name = '';
            this.getData();
          },
          saveColumn() {
            localStorage.setItem(this.$route.path + '-columnSet', JSON.stringify(this.showColumn));
            this.columnVisible = false;
          }
        },
        components: {
          UserEdit,
          UserCreate,
          UserDescribe
        }
    }
</script>

<style scoped>
  .table-header {
    display: flex;
    margin-bottom: 18px;
    justify-content: space-between;
  }
</style>